//
//  TimelyVC.m
//  timelyRain
//
//  Created by Jiafei Wei on 16/7/23.
//  Copyright © 2016年 Jiafei Wei. All rights reserved.
//

#import "TimelyVC.h"
#import "MBTUiColor.h"
#import "JRSegmentControl.h"
#import "RecentHistoryVC.h"
#import "ContactVC.h"
#import "DynamicVC.h"
#import "HarassmentInterception.h"
#import "ContactPersonVC.h"
#import "ChatDemoHelper.h"
#import "DbManage.h"
#import "BindTool.h"
#import "ContactPersonInfo.h"
static const CGFloat kDefaultPlaySoundInterval = 3.0;
@interface TimelyVC ()<UIScrollViewDelegate, JRSegmentControlDelegate,UIGestureRecognizerDelegate>{
    JRSegmentControl *segment;
    BOOL _isDrag;
    BOOL _isDidLayout;
    NSInteger selectIndex;
    ContactVC *contact;
}
@property (weak, nonatomic) IBOutlet UIButton *mark;

- (IBAction)domark:(id)sender;
@property (weak, nonatomic) IBOutlet UIImageView *headPhotos;
@property (weak, nonatomic) IBOutlet UIView *headView;
@property (weak, nonatomic) IBOutlet UIScrollView *contentView;
@property (weak, nonatomic) IBOutlet UIView *titleView;
@property (strong, nonatomic) NSDate *lastPlaySoundDate;
@end

@implementation TimelyVC
- (void)viewDidLoad {
    [super viewDidLoad];
    [_contentView setBackgroundColor:[UIColor yellowColor]];
    [_headView setBackgroundColor:[UIColor colorwithHexString:@"#1186D6"]];
    //[_titleView setBackgroundColor:[UIColor colorwithHexString:@"#046EB8"]];
    _titleView.layer.cornerRadius = 15;
    _titleView.layer.masksToBounds = YES;
//    _titleView.layer.borderWidth = 1.0;
//    _titleView.layer.borderColor = [[UIColor colorwithHexString:@"#1186D6"] CGColor];
    [self settingPerson];
    [self setHeadPic];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateHeadPic:) name:@"update_url" object:nil];
}
-(void)updateHeadPic:(NSNotification*)sender{
    NSDictionary *dataUser = sender.userInfo;
    NSString *url =[dataUser objectForKey:@"data"];
    [_headPhotos sd_setImageWithURL:[NSURL URLWithString:url]];
}

-(void)setHeadPic{
    NSMutableArray *array =[[DbManage shareDbManage]queryPersonInfoByUserId:[BindTool share].bindInfo.phone_number];
    if (array.count!=0) {
        ContactPersonInfo *info = [array objectAtIndex:0];
        _headPhotos.layer.masksToBounds=YES;
        _headPhotos.layer.cornerRadius=_headPhotos.frame.size.height/2;
        [_headPhotos sd_setImageWithURL:[NSURL URLWithString:info.head_pic]];
    }
}
/** 设置segment */
- (void)setupSegmentControl
{
    //设置titleView
    //CGRect frame =_titleView.frame;
    CGRect rr=_titleView.bounds;
    segment = [[JRSegmentControl alloc]initWithFrame:CGRectMake(0, 0, rr.size.width, 30)];
    //segment = [[JRSegmentControl alloc]initWithFrame:frame];
    segment.cornerRadius = 15;
    segment.titleColor = [UIColor whiteColor];
    segment.indicatorViewColor = [UIColor whiteColor];
    segment.backgroundColor = [UIColor colorwithHexString:@"#046EB8"];
    //segment.titles = @[@"最近纪录", @"联系人", @"动态"];
    segment.titles = @[@"最近纪录", @"联系人"];
    segment.delegate = self;
    [segment setSelectedIndex:selectIndex];
//    segment.layer.borderWidth = 1.0;
//    segment.layer.borderColor = [[UIColor colorwithHexString:@"#1186D6"] CGColor];
//        _titleView.layer.borderWidth = 1.0;
//        _titleView.layer.borderColor = [[UIColor colorwithHexString:@"#1186D6"] CGColor];
    [_titleView addSubview:segment];
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
}


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    _isDidLayout =true;
}
-(void)viewWillLayoutSubviews{
    //在这里得真正的控件的frame去处理
    [super viewWillLayoutSubviews];
    self.navigationController.navigationBarHidden =YES;
    if (!_isDidLayout) {
        [self setupSegmentControl];
        [self setupViewControllers];
}
}

/** 设置子视图控制器，这个方法必须在viewDidLoad方法里执行，否则子视图控制器各项属性为空 */
- (void)setupViewControllers
{
    CGRect rr =_contentView.bounds;
    _history = [[ConversationListController alloc]init];
    [ChatDemoHelper shareHelper].conversationListVC =_history;
    [self addChildViewController:_history];
    _history.view.frame = CGRectMake(0, rr.origin.y, rr.size.width, rr.size.height);
    [_contentView addSubview:_history.view];
    
     contact = [[ContactVC alloc]initWithNibName:@"ContactVC" bundle:nil];
    [self addChildViewController:contact];
    contact.view.frame = CGRectMake(rr.size.width,rr.origin.y, rr.size.width, rr.size.height);
    [_contentView addSubview:contact.view];
    
//    DynamicVC *dyna = [[DynamicVC alloc]initWithNibName:@"DynamicVC" bundle:nil];
//    [self addChildViewController:dyna];
//    dyna.view.frame = CGRectMake(rr.size.width *2,rr.origin.y,rr.size.width, rr.size.height);
//    [_contentView addSubview:dyna.view];
    [_contentView setContentSize:CGSizeMake(rr.size.width *2,0)];
    
    _contentView.pagingEnabled = YES;
    _contentView.delegate = self;
}
- (void)playSoundAndVibration{
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
        return;
    }
    
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    // 收到消息时，震动
    [[EMCDDeviceManager sharedInstance] playVibration];
}


#pragma mark - UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [segment selectedBegan];
    _isDrag = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (_isDrag) {
        CGFloat percent = scrollView.contentOffset.x / scrollView.contentSize.width;
        [segment setIndicatorViewPercent:percent];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (decelerate == NO) {
        [segment selectedEnd];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger index = scrollView.contentOffset.x / scrollView.frame.size.width;
    [segment setSelectedIndex:index];
    selectIndex =index;
    if (selectIndex==1) {
        _headPhotos.hidden=NO;
    }else{
        _headPhotos.hidden=YES;
    }
    _isDrag = NO;
}

#pragma mark - JRSegmentControlDelegate

- (void)segmentControl:(JRSegmentControl *)segment didSelectedIndex:(NSInteger)index {
    CGFloat X = index * self.view.frame.size.width;
    CGFloat Y = _contentView.bounds.origin.y;
    [_contentView setContentOffset:CGPointMake(X, Y) animated:YES];
    selectIndex=index;
    if (selectIndex==1) {
        _headPhotos.hidden=NO;
    }else{
        _headPhotos.hidden=YES;
    }
}

- (BOOL)shouldAutorotate
{
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

- (IBAction)domark:(id)sender {
    HarassmentInterception *h =[[HarassmentInterception alloc]init];
    [self.navigationController pushViewController:h animated:YES];
}
-(void)settingPerson{
    _headPhotos.userInteractionEnabled = YES;
    UITapGestureRecognizer *addTapGest = [[UITapGestureRecognizer alloc] init];
    addTapGest.numberOfTapsRequired = 1;
    addTapGest.delegate = self;
    [_headPhotos addGestureRecognizer:addTapGest];
    [addTapGest addTarget:self action:@selector(addTapView:)];
}
- (void)addTapView:(UITapGestureRecognizer *)addTapGest{
    ContactPersonVC *add =[[ContactPersonVC alloc]init];
    [self.navigationController pushViewController:add animated:YES];
}
-(void)refrshContact{
    NSLog(@"是否是回调回来的啊");
    [contact refrshContact];
}
@end
